using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace GenerativeAgents.Core
{
    /// <summary>
    /// 洞察生成器
    /// 负责基于记忆和上下文生成深层洞察
    /// </summary>
    public class InsightGenerator
    {
        private Dictionary<string, string> insightTemplates;
        private List<string> insightConnectors;
        private Dictionary<string, float> insightTypeWeights;
        
        public InsightGenerator()
        {
            InitializeGenerator();
        }
        
        /// <summary>
        /// 初始化洞察生成器
        /// </summary>
        private void InitializeGenerator()
        {
            // 初始化洞察模板
            insightTemplates = new Dictionary<string, string>
            {
                // 社交洞察模板
                ["social_pattern"] = "I notice that {person} tends to {behavior} when {condition}. This suggests {conclusion}.",
                ["relationship_insight"] = "My relationship with {person} seems to be {state} because {reason}. I should {action}.",
                ["social_preference"] = "I tend to feel {emotion} when {social_situation}. This indicates that I {preference}.",
                
                // 行为模式洞察
                ["behavior_pattern"] = "I consistently {action} at {time} in {location}. This pattern shows that {insight}.",
                ["routine_insight"] = "My daily routine reveals that I prioritize {priority} over {alternative}. This reflects {value}.",
                ["habit_observation"] = "I've developed a habit of {habit} which {effect}. This {evaluation}.",
                
                // 情感洞察
                ["emotional_trigger"] = "I feel {emotion} whenever {trigger}. This emotional response suggests {understanding}.",
                ["mood_pattern"] = "My mood changes from {initial_mood} to {final_mood} when {condition}. This pattern indicates {insight}.",
                ["emotional_growth"] = "I'm becoming more {trait} in {situation}. This growth shows that {development}.",
                
                // 目标和价值观洞察
                ["goal_progress"] = "My progress towards {goal} has been {status} because {reason}. I need to {adjustment}.",
                ["value_conflict"] = "I experienced conflict between {value1} and {value2} when {situation}. This reveals {insight}.",
                ["priority_shift"] = "I'm starting to value {new_priority} more than {old_priority}. This shift indicates {change}.",
                
                // 环境洞察
                ["location_preference"] = "I feel most {emotion} in {location} because {reason}. This place {significance}.",
                ["environmental_impact"] = "The environment of {location} influences my {behavior}. This shows {connection}.",
                ["spatial_pattern"] = "I tend to {action} in {location_type}. This spatial preference reflects {insight}."
            };
            
            // 洞察连接词
            insightConnectors = new List<string>
            {
                "This suggests that", "This indicates", "This reveals", "This shows", "This means",
                "This implies", "This demonstrates", "This reflects", "This points to", "This leads me to believe"
            };
            
            // 洞察类型权重
            insightTypeWeights = new Dictionary<string, float>
            {
                ["social"] = 1.2f,
                ["emotional"] = 1.1f,
                ["behavioral"] = 1.0f,
                ["goal"] = 1.3f,
                ["environmental"] = 0.9f
            };
        }
        
        /// <summary>
        /// 生成基于焦点的洞察
        /// </summary>
        public MemoryNode GenerateInsight(string focusPoint, List<MemoryNode> relatedMemories, ILanguageModel languageModel, ScratchMemory scratchMemory)
        {
            try
            {
                if (relatedMemories.Count < 2)
                {
                    return null;
                }
                
                // 分析记忆模式
                var patterns = AnalyzeMemoryPatterns(relatedMemories, focusPoint);
                
                // 选择合适的洞察类型
                var insightType = DetermineInsightType(focusPoint, patterns);
                
                // 生成洞察内容
                string insightContent;
                if (languageModel != null)
                {
                    insightContent = GenerateInsightWithLLM(focusPoint, relatedMemories, patterns, languageModel, scratchMemory);
                }
                else
                {
                    insightContent = GenerateInsightWithTemplate(focusPoint, relatedMemories, patterns, insightType);
                }
                
                if (string.IsNullOrEmpty(insightContent))
                {
                    return null;
                }
                
                // 计算洞察重要性
                var importance = CalculateInsightImportance(insightContent, relatedMemories, insightType);
                
                // 创建洞察记忆节点
                var insightNode = MemoryNode.CreateThought(insightContent, importance, scratchMemory.currentLocation, scratchMemory.currentLocationName);
                insightNode.type = MemoryType.Reflection;
                
                // 建立与相关记忆的连接
                foreach (var memory in relatedMemories.Take(5)) // 限制连接数量
                {
                    insightNode.AddRelatedMemory(memory.nodeId);
                }
                
                // 添加洞察标签
                insightNode.keywords.Add("insight");
                insightNode.keywords.Add(insightType);
                insightNode.keywords.Add("reflection");
                
                return insightNode;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[InsightGenerator] Error generating insight for focus '{focusPoint}': {ex.Message}");
                return null;
            }
        }
        
        /// <summary>
        /// 生成整体性洞察
        /// </summary>
        public MemoryNode GenerateOverallInsight(List<MemoryNode> memories, ILanguageModel languageModel, ScratchMemory scratchMemory)
        {
            try
            {
                // 分析整体模式
                var overallPatterns = AnalyzeOverallPatterns(memories);
                
                // 生成整体洞察
                string insightContent;
                if (languageModel != null)
                {
                    var prompt = CreateOverallInsightPrompt(memories, overallPatterns, scratchMemory);
                    insightContent = languageModel.GenerateResponse(prompt, 0.8f, 100);
                }
                else
                {
                    insightContent = GenerateOverallInsightTemplate(overallPatterns, scratchMemory);
                }
                
                if (string.IsNullOrEmpty(insightContent))
                {
                    return null;
                }
                
                var importance = CalculateInsightImportance(insightContent, memories, "overall");
                var insightNode = MemoryNode.CreateThought(insightContent, importance, scratchMemory.currentLocation, scratchMemory.currentLocationName);
                insightNode.type = MemoryType.Reflection;
                insightNode.keywords.AddRange(new[] { "insight", "overall", "pattern", "reflection" });
                
                return insightNode;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[InsightGenerator] Error generating overall insight: {ex.Message}");
                return null;
            }
        }
        
        /// <summary>
        /// 生成社交洞察
        /// </summary>
        public MemoryNode GenerateSocialInsight(List<MemoryNode> socialMemories, ILanguageModel languageModel, ScratchMemory scratchMemory)
        {
            try
            {
                // 分析社交模式
                var socialPatterns = AnalyzeSocialPatterns(socialMemories, scratchMemory);
                
                // 生成社交洞察
                string insightContent;
                if (languageModel != null)
                {
                    var prompt = CreateSocialInsightPrompt(socialMemories, socialPatterns, scratchMemory);
                    insightContent = languageModel.GenerateResponse(prompt, 0.7f, 80);
                }
                else
                {
                    insightContent = GenerateSocialInsightTemplate(socialPatterns, scratchMemory);
                }
                
                if (string.IsNullOrEmpty(insightContent))
                {
                    return null;
                }
                
                var importance = CalculateInsightImportance(insightContent, socialMemories, "social");
                var insightNode = MemoryNode.CreateThought(insightContent, importance, scratchMemory.currentLocation, scratchMemory.currentLocationName);
                insightNode.type = MemoryType.Reflection;
                insightNode.keywords.AddRange(new[] { "insight", "social", "relationship", "reflection" });
                
                return insightNode;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[InsightGenerator] Error generating social insight: {ex.Message}");
                return null;
            }
        }
        
        /// <summary>
        /// 分析记忆模式
        /// </summary>
        private Dictionary<string, object> AnalyzeMemoryPatterns(List<MemoryNode> memories, string focusPoint)
        {
            var patterns = new Dictionary<string, object>();
            
            try
            {
                // 时间模式分析
                var timeGroups = memories.GroupBy(m => m.createdTime.Hour).ToList();
                if (timeGroups.Count > 1)
                {
                    var mostActiveHour = timeGroups.OrderByDescending(g => g.Count()).First().Key;
                    patterns["most_active_hour"] = mostActiveHour;
                }
                
                // 位置模式分析
                var locationGroups = memories.Where(m => !string.IsNullOrEmpty(m.locationName))
                    .GroupBy(m => m.locationName).ToList();
                if (locationGroups.Count > 0)
                {
                    var mostCommonLocation = locationGroups.OrderByDescending(g => g.Count()).First().Key;
                    patterns["most_common_location"] = mostCommonLocation;
                }
                
                // 参与者模式分析
                var allParticipants = memories.Where(m => m.participants != null)
                    .SelectMany(m => m.participants)
                    .Where(p => !string.IsNullOrEmpty(p))
                    .GroupBy(p => p)
                    .OrderByDescending(g => g.Count())
                    .ToList();
                
                if (allParticipants.Count > 0)
                {
                    patterns["frequent_participants"] = allParticipants.Take(3).Select(g => g.Key).ToList();
                }
                
                // 重要性模式分析
                var avgImportance = memories.Average(m => m.poignancy);
                patterns["average_importance"] = avgImportance;
                
                var highImportanceCount = memories.Count(m => m.poignancy >= 7);
                patterns["high_importance_count"] = highImportanceCount;
                
                // 关键词频率分析
                var allKeywords = memories.Where(m => m.keywords != null)
                    .SelectMany(m => m.keywords)
                    .GroupBy(k => k)
                    .OrderByDescending(g => g.Count())
                    .Take(5)
                    .Select(g => g.Key)
                    .ToList();
                
                patterns["common_keywords"] = allKeywords;
                
                // 记忆类型分布
                var typeDistribution = memories.GroupBy(m => m.type)
                    .ToDictionary(g => g.Key.ToString(), g => g.Count());
                patterns["type_distribution"] = typeDistribution;
                
            }
            catch (Exception ex)
            {
                Debug.LogError($"[InsightGenerator] Error analyzing memory patterns: {ex.Message}");
            }
            
            return patterns;
        }
        
        /// <summary>
        /// 分析整体模式
        /// </summary>
        private Dictionary<string, object> AnalyzeOverallPatterns(List<MemoryNode> memories)
        {
            var patterns = new Dictionary<string, object>();
            
            try
            {
                // 时间趋势分析
                var recentMemories = memories.Where(m => m.createdTime >= DateTime.Now.AddHours(-24)).Count();
                var olderMemories = memories.Count - recentMemories;
                patterns["recent_vs_older"] = new { recent = recentMemories, older = olderMemories };
                
                // 情感趋势（基于关键词）
                var emotionalKeywords = new Dictionary<string, string>
                {
                    ["happy"] = "positive", ["excited"] = "positive", ["joy"] = "positive",
                    ["sad"] = "negative", ["angry"] = "negative", ["frustrated"] = "negative",
                    ["calm"] = "neutral", ["peaceful"] = "neutral", ["content"] = "neutral"
                };
                
                var emotionCounts = new Dictionary<string, int> { ["positive"] = 0, ["negative"] = 0, ["neutral"] = 0 };
                
                foreach (var memory in memories)
                {
                    if (memory.keywords != null)
                    {
                        foreach (var keyword in memory.keywords)
                        {
                            if (emotionalKeywords.ContainsKey(keyword.ToLower()))
                            {
                                emotionCounts[emotionalKeywords[keyword.ToLower()]]++;
                            }
                        }
                    }
                }
                
                patterns["emotional_distribution"] = emotionCounts;
                
                // 活动多样性
                var activityKeywords = memories.Where(m => m.keywords != null)
                    .SelectMany(m => m.keywords)
                    .Where(k => IsActivityKeyword(k))
                    .Distinct()
                    .Count();
                
                patterns["activity_diversity"] = activityKeywords;
                
            }
            catch (Exception ex)
            {
                Debug.LogError($"[InsightGenerator] Error analyzing overall patterns: {ex.Message}");
            }
            
            return patterns;
        }
        
        /// <summary>
        /// 分析社交模式
        /// </summary>
        private Dictionary<string, object> AnalyzeSocialPatterns(List<MemoryNode> socialMemories, ScratchMemory scratchMemory)
        {
            var patterns = new Dictionary<string, object>();
            
            try
            {
                // 社交频率分析
                var conversationCount = socialMemories.Count(m => m.type == MemoryType.Chat);
                patterns["conversation_frequency"] = conversationCount;
                
                // 社交伙伴分析
                var socialPartners = socialMemories.Where(m => m.participants != null)
                    .SelectMany(m => m.participants)
                    .Where(p => p != scratchMemory.agentName)
                    .GroupBy(p => p)
                    .OrderByDescending(g => g.Count())
                    .Take(5)
                    .ToDictionary(g => g.Key, g => g.Count());
                
                patterns["social_partners"] = socialPartners;
                
                // 关系质量分析（基于短期记忆）
                var relationshipQuality = new Dictionary<string, string>();
                foreach (var partner in socialPartners.Keys)
                {
                    if (scratchMemory.relationshipStates.ContainsKey(partner))
                    {
                        var relationship = scratchMemory.relationshipStates[partner];
                        if (relationship >= 0.5f)
                            relationshipQuality[partner] = "positive";
                        else if (relationship <= -0.5f)
                            relationshipQuality[partner] = "negative";
                        else
                            relationshipQuality[partner] = "neutral";
                    }
                }
                
                patterns["relationship_quality"] = relationshipQuality;
                
                // 社交环境分析
                var socialLocations = socialMemories.Where(m => !string.IsNullOrEmpty(m.locationName))
                    .GroupBy(m => m.locationName)
                    .OrderByDescending(g => g.Count())
                    .Take(3)
                    .Select(g => g.Key)
                    .ToList();
                
                patterns["social_locations"] = socialLocations;
                
            }
            catch (Exception ex)
            {
                Debug.LogError($"[InsightGenerator] Error analyzing social patterns: {ex.Message}");
            }
            
            return patterns;
        }
        
        /// <summary>
        /// 确定洞察类型
        /// </summary>
        private string DetermineInsightType(string focusPoint, Dictionary<string, object> patterns)
        {
            var lowerFocus = focusPoint.ToLower();
            
            if (lowerFocus.Contains("relationship") || lowerFocus.Contains("social") || lowerFocus.Contains("friend"))
                return "social";
            
            if (lowerFocus.Contains("feeling") || lowerFocus.Contains("emotion") || lowerFocus.Contains("mood"))
                return "emotional";
            
            if (lowerFocus.Contains("goal") || lowerFocus.Contains("plan") || lowerFocus.Contains("objective"))
                return "goal";
            
            if (lowerFocus.Contains("location") || lowerFocus.Contains("place") || lowerFocus.Contains("environment"))
                return "environmental";
            
            if (lowerFocus.Contains("habit") || lowerFocus.Contains("routine") || lowerFocus.Contains("behavior"))
                return "behavioral";
            
            return "general";
        }
        
        /// <summary>
        /// 使用语言模型生成洞察
        /// </summary>
        private string GenerateInsightWithLLM(string focusPoint, List<MemoryNode> memories, Dictionary<string, object> patterns, ILanguageModel languageModel, ScratchMemory scratchMemory)
        {
            try
            {
                var prompt = CreateInsightPrompt(focusPoint, memories, patterns, scratchMemory);
                var response = languageModel.GenerateResponse(prompt, 0.8f, 100);
                
                // 清理和验证响应
                return CleanInsightResponse(response);
            }
            catch (Exception ex)
            {
                Debug.LogError($"[InsightGenerator] Error generating insight with LLM: {ex.Message}");
                return null;
            }
        }
        
        /// <summary>
        /// 创建洞察提示词
        /// </summary>
        private string CreateInsightPrompt(string focusPoint, List<MemoryNode> memories, Dictionary<string, object> patterns, ScratchMemory scratchMemory)
        {
            var prompt = $"Based on my recent experiences about '{focusPoint}', I want to reflect and gain insight.\n\n";
            
            prompt += "Recent relevant memories:\n";
            foreach (var memory in memories.Take(5))
            {
                prompt += $"- {memory.content} (Importance: {memory.poignancy})\n";
            }
            
            prompt += $"\nMy current state: I am {scratchMemory.currentAction} and feeling {scratchMemory.mood}.\n";
            
            if (patterns.ContainsKey("common_keywords"))
            {
                var keywords = patterns["common_keywords"] as List<string>;
                if (keywords != null && keywords.Count > 0)
                {
                    prompt += $"Common themes: {string.Join(", ", keywords)}\n";
                }
            }
            
            prompt += "\nReflecting on this, I realize that ";
            
            return prompt;
        }
        
        /// <summary>
        /// 使用模板生成洞察
        /// </summary>
        private string GenerateInsightWithTemplate(string focusPoint, List<MemoryNode> memories, Dictionary<string, object> patterns, string insightType)
        {
            try
            {
                // 选择合适的模板
                var templateKey = SelectTemplate(insightType, patterns);
                if (!insightTemplates.ContainsKey(templateKey))
                {
                    templateKey = "social_pattern"; // 默认模板
                }
                
                var template = insightTemplates[templateKey];
                
                // 填充模板变量
                return FillTemplate(template, focusPoint, memories, patterns);
            }
            catch (Exception ex)
            {
                Debug.LogError($"[InsightGenerator] Error generating insight with template: {ex.Message}");
                return GenerateFallbackInsight(focusPoint);
            }
        }
        
        /// <summary>
        /// 选择合适的模板
        /// </summary>
        private string SelectTemplate(string insightType, Dictionary<string, object> patterns)
        {
            switch (insightType)
            {
                case "social":
                    return "social_pattern";
                case "emotional":
                    return "emotional_trigger";
                case "behavioral":
                    return "behavior_pattern";
                case "goal":
                    return "goal_progress";
                case "environmental":
                    return "location_preference";
                default:
                    return "social_pattern";
            }
        }
        
        /// <summary>
        /// 填充模板变量
        /// </summary>
        private string FillTemplate(string template, string focusPoint, List<MemoryNode> memories, Dictionary<string, object> patterns)
        {
            var filled = template;
            
            // 基本变量替换
            filled = filled.Replace("{focus}", focusPoint);
            
            // 从模式中提取变量
            if (patterns.ContainsKey("frequent_participants"))
            {
                var participants = patterns["frequent_participants"] as List<string>;
                if (participants != null && participants.Count > 0)
                {
                    filled = filled.Replace("{person}", participants.First());
                }
            }
            
            if (patterns.ContainsKey("most_common_location"))
            {
                filled = filled.Replace("{location}", patterns["most_common_location"].ToString());
            }
            
            if (patterns.ContainsKey("most_active_hour"))
            {
                var hour = (int)patterns["most_active_hour"];
                var timeOfDay = hour < 12 ? "morning" : hour < 18 ? "afternoon" : "evening";
                filled = filled.Replace("{time}", timeOfDay);
            }
            
            // 填充默认值
            filled = filled.Replace("{behavior}", "interact with others");
            filled = filled.Replace("{condition}", "in social situations");
            filled = filled.Replace("{conclusion}", "I value social connections");
            filled = filled.Replace("{emotion}", "comfortable");
            filled = filled.Replace("{action}", "continue building relationships");
            
            return filled;
        }
        
        /// <summary>
        /// 计算洞察重要性
        /// </summary>
        private int CalculateInsightImportance(string insightContent, List<MemoryNode> relatedMemories, string insightType)
        {
            var importance = 6; // 基础重要性
            
            // 基于相关记忆的平均重要性
            if (relatedMemories.Count > 0)
            {
                var avgMemoryImportance = relatedMemories.Average(m => m.poignancy);
                importance += (int)(avgMemoryImportance * 0.3f);
            }
            
            // 基于洞察类型
            if (insightTypeWeights.ContainsKey(insightType))
            {
                importance = (int)(importance * insightTypeWeights[insightType]);
            }
            
            // 基于内容复杂性
            var wordCount = insightContent.Split(' ').Length;
            if (wordCount > 15)
            {
                importance += 1;
            }
            
            return Mathf.Clamp(importance, 1, 10);
        }
        
        /// <summary>
        /// 清理洞察响应
        /// </summary>
        private string CleanInsightResponse(string response)
        {
            if (string.IsNullOrEmpty(response))
                return null;
            
            // 移除多余的空格和换行
            response = response.Trim();
            response = System.Text.RegularExpressions.Regex.Replace(response, @"\s+", " ");
            
            // 确保以句号结尾
            if (!response.EndsWith(".") && !response.EndsWith("!") && !response.EndsWith("?"))
            {
                response += ".";
            }
            
            // 长度限制
            if (response.Length > 200)
            {
                response = response.Substring(0, 197) + "...";
            }
            
            return response;
        }
        
        /// <summary>
        /// 生成备用洞察
        /// </summary>
        private string GenerateFallbackInsight(string focusPoint)
        {
            return $"I notice patterns in my experiences related to {focusPoint}. This suggests I should pay more attention to these situations.";
        }
        
        /// <summary>
        /// 检查是否为活动关键词
        /// </summary>
        private bool IsActivityKeyword(string keyword)
        {
            var activityWords = new HashSet<string>
            {
                "work", "eat", "sleep", "talk", "walk", "read", "write", "play", "study",
                "cook", "clean", "exercise", "shop", "travel", "meet", "visit", "call"
            };
            
            return activityWords.Contains(keyword.ToLower());
        }
        
        // 其他辅助方法的简化实现
        private string CreateOverallInsightPrompt(List<MemoryNode> memories, Dictionary<string, object> patterns, ScratchMemory scratchMemory)
        {
            return $"Looking at my recent experiences, I notice overall patterns in my behavior and thinking. Reflecting on this, I realize that ";
        }
        
        private string CreateSocialInsightPrompt(List<MemoryNode> socialMemories, Dictionary<string, object> patterns, ScratchMemory scratchMemory)
        {
            return $"Considering my social interactions and relationships, I observe certain patterns. This leads me to understand that ";
        }
        
        private string GenerateOverallInsightTemplate(Dictionary<string, object> patterns, ScratchMemory scratchMemory)
        {
            return "I'm developing a better understanding of my overall patterns and behaviors. This helps me grow as a person.";
        }
        
        private string GenerateSocialInsightTemplate(Dictionary<string, object> patterns, ScratchMemory scratchMemory)
        {
            return "My social interactions reveal important aspects of my relationships and communication style.";
        }
    }
}